<?php
namespace app\finance\controller;
use think\Request;
use app\common\controller\Common;
use think\Exception;
use think\Db;
class Cate extends Common
{
	protected $model = null;
	protected $afterActionList = [
        'addOperLog'  =>  ['only'=>'add,del'],
    ];

	public function _initialize()
	{
		parent::_initialize();
		$this->model = new \app\finance\model\Cate;
	}
	/**
	* 支出记账分类
	*/
	public function index()
	{
		if(Request()->isAjax()){
			$data = Request()->param('');
			$ty = $this->cateData($data['ty']);
			$list = $this->model->getCate($ty);
			return $this->jsonList(0, config('status.SUCCESS_ONE'), 0, $list, 1, 1);
		}
		if(Request()->isGet()){
			return $this->fetch('');
		}
	}
	/**
	* 添加支出分类
	*/
	public function add()
	{
		if(Request()->post()){
			$data = Request()->param('');
			$data['ty'] = $this->cateData($data['ty']);
			try{
				$res = $this->model->allowField(true)->validate('Cate.add')->save($data);
				if($res === false){
					$this->error($this->model->getError());
				}
				$this->log_id = $this->model->expend_cate_id;
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				$this->error(config('status.ERROR_FIVE'));
			}
		}
		if(Request()->isGet()){
			return $this->fetch('');
		}
	}
	/**
	* 删除
	*/
	public function del()
	{
		if(Request()->isAjax())
		{
			$data = Request()->param('');
			if(!isset($data['id']) || $data['id'] == ''){
				$this->error(config('status.ERROR_SIX'));
			}
			$this->log_id = implode(',', $data['id']);
			try{
				Db::startTrans();
				$this->model->where('expend_cate_id','in',$data['id'])->delete();
				model('pay')->where('expend_cate_id','in',$data['id'])->delete();
				Db::commit();
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				Db::rollback();
				$this->error(config('status.ERROR_FIVE'));
			}
		}
	}

	/************************************ 私有 **************************************/
	/**
	* 记账分类
	*/
	private function cateData($ty)
	{
		switch($ty){
			case 0: switch(session('admin.admin_type')){
				case 0: return $ty = 0;break;
				case 1:
				case 2:
				return $ty = 1;break;
				default: $this->error('status.ERROR_SIX');break;
			}
			case 1: switch(session('admin.admin_type')){
				case 1: 
				case 2: 
				return $ty = 1;break;
				default: $this->error('status.ERROR_SIX');break;
			}
			case 2: switch(session('admin.admin_type')){
				case 0: return $ty = 2;break;
				default: $this->error('status.ERROR_SIX');break;
			}
			default: $this->error(config('status.ERROR_SIX'));break;
		}
	}
}